$('.datepicker').datepicker({dateFormat: "yy-mm-dd"});

var test = function(days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
};

var colorsOfLines = {
	"Coca Cola": "#ff0000",
	"Fanta": "#ffff00",
	"Sprite": "#9EF0A5",
	"Nestea": "#E0D49B",
	"Vitel": "#0E090F",	
};


loadMachinesData();

function collectData(){
	var data = {};
	data.machineId = $('.id-machine-select').val();
	data.dateFrom = $('input[name="dt_from"]').val();
	data.dateTo = $('input[name="dt_to"]').val();
	
	if( data.dateFrom == '' ){
		var date = data.dateTo != '' ? new Date(data.dateTo) : new Date();
		date.setDate(date.getDate() - 10 );
		data.dateFrom = formatDate(date);
	}
	
	if( data.dateTo == '' ){
		var date = data.dateFrom != '' ? new Date(data.dateFrom) : new Date();		
		date.setDate( date.getDate() + 10 );
		data.dateTo = formatDate(date);
	}
	
	return data;
}

function formatDate( date ){
	date = new Date( date );
	return date.getFullYear() + "-" + ('0' + (date.getMonth() + 1)).slice(-2) + "-" + ('0' + date.getDate()).slice(-2);
}

function refreshChart(){
	
	var period = collectData();		
	var ctx = document.getElementById('chart-statistics').getContext("2d");
	var dates = calculateDates(new Date(period.dateFrom), new Date(period.dateTo), test, 1);
	
	var datasets = prepareDataForChart( dates );
	
	if( typeof( chart ) != 'undefined' ){
		chart.destroy();
	}
	
	if( datasets.length > 0 ){
		var data = {
		    labels: dates,
		    datasets: datasets,
		};
	
		var html = '<div class="id-legend">';
		for( var i in colorsOfLines ){
			html += '<span><span style="background-color:' + colorsOfLines[i] + '; height: 10px; width: 10px; float: left; border: 1px black;"></span><span style="float:left;">' + i + '</span></span><br />'
		}
		html += '</div>';
		$('.id-legend').html('');
		
		var options = { 
			legendTemplate: html, 
			datasetFill: false, 
			datasetStroke: true, 
			datasetStrokeWidth : 0, 
			bezierCurve: false, 
			scaleOverride: true, 
			scaleSteps: 15, 
			scaleStepWidth: 2, 
			scaleStartValue: 0 
		};
		
		chart = new Chart(ctx).Line(data, options);
		$('.id-chart-container').show();
		$('.id-legend').append( chart.generateLegend() );
	} else {				
		$('.id-legend').html('');
		$('.id-chart-container').hide();
		alert('Brak danych zakupu dla podanego automatu.');
	}
}

function prepareDataForChart( datesPeriod ){
	
	var map = loadStatistics();
	
	var result = [];
	var machines = eliminateDuplicates( map.map( function(e){ return e[1]; }) );
	for( var i in machines ){		
		var sequence = {
			name: machines[i],
			trademarks: []
		}; 
		
		var filterData = map.filter( function(e){ return e[1] == machines[i]; });
		var trademarks = eliminateDuplicates( filterData.map( function(e){ return e[0]; } ) );
		for( var j in trademarks ){					
			var trademark = {
				'name': trademarks[j],
				'points': []			
			};
			
			var trademarkGroup = map.filter( function(e){ return e[0] == trademarks[j]; } );
			var dates = eliminateDuplicates( trademarkGroup.map( function(e){ return e[2].split(" ")[0]; } ) );
			for( var k in dates ){
				var amount = trademarkGroup.filter( function(e){ return e[2].split(" ")[0] == dates[k]; }).length;

				trademark['points'].push([dates[k], amount]);
			}
			sequence['trademarks'].push( trademark );
		}
		result.push( sequence );			
	}
		
	var datasets = [];
	for( var i in result ){
		for( var w in result[i].trademarks ){

			var dataset = {
				label: result[i].trademarks[w].name,
				//fillColor: colorsOfLines[result[i].trademarks[w].name],
	            strokeColor: colorsOfLines[result[i].trademarks[w].name],
	            pointColor: colorsOfLines[result[i].trademarks[w].name],
	            pointStrokeColor: null,
	            pointHighlightFill: null,
	            pointHighlightStroke: colorsOfLines[result[i].trademarks[w].name]
			};
			var data = [];
			for( var j in datesPeriod ){			
				var element = result[i].trademarks[w]['points'].filter( function(e){ 
					return e[0] == datesPeriod[j]; });
				if( element.length > 0 ){
					data.push( element[0][1] );
				} else {
					data.push( 0 );
				}
			}
			dataset.data = data;
			datasets.push( dataset );			
		}
	}
	
	return datasets;		
}

function eliminateDuplicates(arr) {
	  var i,
	      len=arr.length,
	      out=[],
	      obj={};

	  for (i=0;i<len;i++) {
		  obj[arr[i]]=0;
	  }
	  for (i in obj) {
		  out.push(i);
	  }
	  return out;
}

function calculateDates( startDate, endDate, addFn, interval ){
	var interval = interval || 1;

	var retVal = [];
	var current = new Date(startDate);

	while (current <= endDate) {
		var date = new Date(current);
		retVal.push( date.getFullYear() + "-" + ('0' + (date.getMonth() + 1)).slice(-2) + "-" + ('0' + date.getDate()).slice(-2) );		
		current = addFn.call(current, interval);
	}

	return retVal;
}

function loadStatistics(){
	var ret = [];
	$.ajax({
		'async': false,
		'type': 'POST', 
		'data': collectData(),
		'url': 'LoadStatisticsServlet',
		'dataType': 'json',
		'success': function( result ){
			ret = result;
		}
	});
	
	return ret;
}

function loadMachinesData(){
	$.ajax({
		'type': 'GET',
		'url': 'LoadMachinesDataServlet',
		'dataType': 'json',
		'success': function( result ){
			buildPage( result );
		}
	});	
}

function buildPage( result ){
	buildStartChoiceSelect( result.machines );
}

function buildStartChoiceSelect( machines ){
	var options = [];
	var hg = new HtmlGenerator();
	for( var i in machines ){
		options.push( {name: machines[i].machineName, value: machines[i].id });
	}
	$('.id-machine-choice').append( hg.select(options, 'id-machine-select') );
}

$('.id-show-statistics').click( refreshChart );

